from datetime import datetime

import bcrypt
import pymysql
from flask import jsonify, render_template, request, current_app, abort
from config.config import DB_CONFIG
from werkzeug.utils import secure_filename
import os
from config.config import url
import time


def get_url():
    return url


def get_db_connection():
    return pymysql.connect(**DB_CONFIG)


def shipments():
    username = request.cookies.get('username')
    token = request.cookies.get('token')

    # 检查用户名和令牌是否存在
    if not username or not token:
        abort(402, description="未授权：缺少用户名或令牌")

    # 检查令牌是否有效
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT `token` FROM `token` WHERE `username` = %s", (username,))
    results = cursor.fetchall()

    # 遍历查询结果，检查是否有匹配的token
    for result in results:
        if result[0] == token:
            break
    else:
        cursor.close()
        conn.close()
        abort(403, description="未授权：无效的令牌")
    if not username:
        return jsonify({'data': {'code': 400, 'msg': '未授权：缺少用户名'}})

    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT `UID` FROM `userinfo` WHERE `username` = %s", (username,))
    result = cursor.fetchone()
    if not result:
        return jsonify({'data': {'code': 400, 'msg': '未找到用户'}})

    uid = result[0]
    cursor.execute(
        "SELECT `ProductID`, `ProductName`, `ImageURL`, `who_buy`, `success_shipments`, `IsSold` FROM `products` WHERE `OwnerID` = %s AND `who_buy` IS NOT NULL",
        (uid,))
    products = cursor.fetchall()

    data = []
    for product in products:
        data.append({
            'ProductID': product[0],
            'ProductName': product[1],
            'ImageURL': product[2],
            'who_buy': product[3],
            'success_shipments': product[4],
            'IsSold': product[5]  # 添加 IsSold 字段
        })

    return jsonify({'data': {'code': 200, 'msg': '查询成功', 'products': data}})


def dont_shipments():
    username = request.cookies.get('username')
    token = request.cookies.get('token')

    # 检查用户名和令牌是否存在
    if not username or not token:
        abort(402, description="未授权：缺少用户名或令牌")

    # 检查令牌是否有效
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT `token` FROM `token` WHERE `username` = %s", (username,))
    results = cursor.fetchall()

    # 遍历查询结果，检查是否有匹配的token
    for result in results:
        if result[0] == token:
            break
    else:
        cursor.close()
        conn.close()
        abort(403, description="未授权：无效的令牌")
    data = request.get_json()
    product_id = data.get('product_id')
    if not product_id:
        return jsonify({'data': {'code': 400, 'msg': '缺少商品ID'}})

    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("UPDATE `products` SET `who_buy` = NULL WHERE `ProductID` = %s", (product_id,))
    conn.commit()

    return jsonify({'data': {'code': 200, 'msg': '取消发货成功'}})

def success_shipments():
    username = request.cookies.get('username')
    token = request.cookies.get('token')

    # 检查用户名和令牌是否存在
    if not username or not token:
        abort(402, description="未授权：缺少用户名或令牌")

    # 检查令牌是否有效
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT `token` FROM `token` WHERE `username` = %s", (username,))
    results = cursor.fetchall()

    # 遍历查询结果，检查是否有匹配的token
    for result in results:
        if result[0] == token:
            break
    else:
        cursor.close()
        conn.close()
        abort(403, description="未授权：无效的令牌")
    data = request.get_json()
    product_id = data.get('product_id')
    if not product_id:
        return jsonify({'data': {'code': 400, 'msg': '缺少商品ID'}})

    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("UPDATE `products` SET `success_shipments` = 1 WHERE `ProductID` = %s", (product_id,))
    conn.commit()

    return jsonify({'data': {'code': 200, 'msg': '已发货成功'}})
class Shipments:
    def __init__(self, app):
        self.app = app
        self.app.add_url_rule('/api/shipments', view_func=shipments, methods=['GET'])
        self.app.add_url_rule('/api/dont_shipments', view_func=dont_shipments, methods=['POST'])
        self.app.add_url_rule('/api/success_shipments', view_func=success_shipments, methods=['POST'])
